package com.gzittc.gzgm.gm.model.protocol;

import android.os.Message;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.json.JSONObject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * 请求封装基类
 *
 * @author YZC
 *         created at 2017-12-09
 */
public class BaseProtocol {
    private Retrofit retrofit;
    private IHttpService httpService;

    public BaseProtocol() {
        retrofit = RetrofitManger.getInstance().getRetrofit();
        httpService = RetrofitManger.getInstance().getHttpService();
    }

    public IHttpService getHttpService() {
        return httpService;
    }

    /**
     * @param call
     * @param reqtype  请求的类型
     * @param callback 回调
     * @param clazz    对应的bean类
     * @param <T>
     */
    public <T> void execute(Call<JsonObject> call, final HttpCallback callback, final Class<T> clazz, final int reqtype) {
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                try {
                    String jsonStr = response.body().toString();
                    JSONObject jsonobject = new JSONObject(jsonStr);
                    if (jsonobject.getInt("code") == 0) {//如果请求的数据正确
                        Gson gson = new Gson();
                        T t = gson.fromJson(jsonStr, clazz);
                        Message msg = new Message();
                        msg.obj = t;
                        if (callback != null) {
                            callback.onHttpSuccess(reqtype, msg);
                        }
                    } else {
                        String error = jsonobject.getString("msg");
                        if (callback != null) {
                            callback.onHttpError(error);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (callback != null) {
                        callback.onHttpError(e.getMessage());
                    }
                }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                if (callback != null) {
                    callback.onHttpError(t.getMessage());
                }
            }
        });
    }

    public interface HttpCallback {
        //请求成功
        void onHttpSuccess(int reqtype, Message msg);

        //请求失败
        void onHttpError(String error);
    }

}
